<?php


namespace app\unify\model;


use think\Model;
use app\unify\model\User as UserModel;

/**
 * 角色表
 * @package app\unify\model
 */
class Role extends Base
{
    public function auths()
    {
        return $this->belongsToMany(
            Auth::class,
            RoleAuth::class,
            'auth_id',
            'role_id'
        );
    }

    public function authIds(){
        return $this->hasMany(RoleAuth::class, 'role_id', 'id');
    }

    public function getAuthNamesAttr($value, $data)
    {
        $authNameList = [];
        foreach ($data['auths'] as $auth) {
            $authNameList[] = $auth['name'];
        }

        return implode(',', $authNameList);
    }

    public static function onBeforeDelete(Model $model): bool
    {
        $userIdsList = UserRole::where([
            ['role_id', '=', $model->getData($model->getPk())]
        ])->column("user_id");

        $nickList = UserModel::where([
            [UserModel::getPrimaryKey(), 'in', $userIdsList]
        ])->column("nick");

        if (!empty($nickList)) {
            throw new \Exception("监测到{$model->getData('name')}角色下存在用户：" . implode('、', $nickList) ."，请先移除后重试。");
        }

        return true;
    }
}